package com.hyzx.qbasic.admin.domain.service.impl;

import com.github.pagehelper.PageInfo;
import com.hyzx.qbasic.admin.model.constant.ProcessConfigKeyConst;
import com.hyzx.qbasic.admin.model.enums.CmsContentStatus;
import com.hyzx.qbasic.admin.model.enums.ProcessInstanceStatus;
import com.hyzx.qbasic.admin.model.po.CmsContentPO;
import com.hyzx.qbasic.admin.model.po.CmsPagedContentPO;
import com.hyzx.qbasic.admin.model.po.ProcessInstancePO;
import com.hyzx.qbasic.admin.model.vo.req.admin.AddCmsContentReq;
import com.hyzx.qbasic.admin.model.vo.req.admin.GetCmsContentListReq;
import com.hyzx.qbasic.admin.model.vo.res.BaseOperationRes;
import com.hyzx.qbasic.admin.common.util.OperationResUtils;
import com.hyzx.qbasic.admin.domain.repository.ICmsContentRepository;
import com.hyzx.qbasic.admin.domain.service.ICmsContentService;
import com.hyzx.qbasic.admin.domain.service.IProcessFacadeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by 黄江华 on 2018/7/30
 */

@Service
public class CmsContentServiceImpl implements ICmsContentService {

    @Autowired
    private ICmsContentRepository contentRepository;

    @Autowired
    private IProcessFacadeService processFacadeService;

    @Override
    public PageInfo<CmsPagedContentPO> getPagedCmsContentList(GetCmsContentListReq req) {
        return contentRepository.getPagedCmsContentList(req);
    }

    @Override
    public BaseOperationRes addCmsContent(AddCmsContentReq req) {
        CmsContentPO contentPO = new CmsContentPO();
        contentPO.setContentId(req.getContentId());
        contentPO.setChannelId(req.getChannelIdList().get(req.getChannelIdList().size() - 1));
        contentPO.setUserId(req.getUserId());
        contentPO.setUserName(req.getUserName());
        contentPO.setTitle(req.getTitle());
        contentPO.setTitleImg(req.getTitleImg());
        contentPO.setAuthor(req.getAuthor());
        contentPO.setOrigin(req.getOrigin());
        contentPO.setOriginUrl(req.getOriginUrl());
        contentPO.setDescription(req.getDescription());
        contentPO.setTopLevel(req.getTopLevel());
        contentPO.setReleaseDate(req.getReleaseDate());
        contentPO.setContent(req.getContent());
        contentPO.setContentStatus(CmsContentStatus.DRAFT.ordinal());
        contentPO.setCreateTime(new Date());
        contentPO.setUpdateTime(new Date());

        boolean success = contentRepository.addCmsContent(contentPO);
        if (!success)
            return OperationResUtils.fail("新增内容失败");

        return OperationResUtils.success();
    }

    @Override
    public BaseOperationRes editCmsContent(AddCmsContentReq req) {
        //检查内容是否存在
        CmsContentPO existedCmsContent = contentRepository.getCmsContentInfo(req.getContentId());
        if (existedCmsContent == null)
            return OperationResUtils.fail("内容不存在");

        CmsContentPO contentPO = new CmsContentPO();
        contentPO.setContentId(req.getContentId());
        contentPO.setChannelId(req.getChannelIdList().get(req.getChannelIdList().size() - 1));
        contentPO.setUserId(req.getUserId());
        contentPO.setUserName(req.getUserName());
        contentPO.setTitle(req.getTitle());
        contentPO.setTitleImg(req.getTitleImg());
        contentPO.setAuthor(req.getAuthor());
        contentPO.setOrigin(req.getOrigin());
        contentPO.setOriginUrl(req.getOriginUrl());
        contentPO.setDescription(req.getDescription());
        contentPO.setTopLevel(req.getTopLevel());
        contentPO.setReleaseDate(req.getReleaseDate());
        contentPO.setContent(req.getContent());
        contentPO.setContentStatus(CmsContentStatus.DRAFT.ordinal());
        contentPO.setUpdateTime(new Date());

        boolean success = contentRepository.editCmsContent(contentPO);
        if (!success)
            return OperationResUtils.fail("编辑内容失败");

        return OperationResUtils.success();
    }

    @Override
    public CmsContentPO getCmsContentInfo(String contentId) {
        return contentRepository.getCmsContentInfo(contentId);
    }

    @Override
    public PageInfo<CmsPagedContentPO> getPagedAuditListInfo(int pageNum, int pageSize, int userId) {
        return contentRepository.getAuditList(pageNum, pageSize, userId);
    }

    @Override
    public BaseOperationRes publish(int publisher, List<String> contentIdList) {
        for (String contentId : contentIdList) {
            Integer channelId = contentRepository.getContentChannel(contentId);
            if (channelId == null || channelId == 0)
                return OperationResUtils.fail("内容发布失败，内容所属栏目不能为空");

            //启动流程实例
            String processConfigKey = ProcessConfigKeyConst.PROCESS_CONFIG_KEY_CMS + channelId;
            ProcessInstancePO processInstance = processFacadeService.startProcessInstanceByKey(
                    processConfigKey, contentId, String.valueOf(publisher));

            if (processInstance == null) {
                return OperationResUtils.fail("内容发布失败，审批流程启动失败");
            }

            if (ProcessInstanceStatus.SUCCESS.ordinal() == processInstance.getProcessStatus()) {
                //如果审核级别为0，则直接更改状态为审核通过
                contentRepository.auditComplete(contentId, CmsContentStatus.AUDITED.ordinal());
            } else {
                contentRepository.publish(contentId);
            }
        }

        return OperationResUtils.success();
    }

    @Override
    public BaseOperationRes audit(int auditor, String contentId) {
        boolean success = processFacadeService.completeTaskByBusinessKey(contentId, String.valueOf(auditor), null, false);
        if (!success) {
            return OperationResUtils.fail("内容审批失败");
        }

        //判断是否审核结束
        ProcessInstancePO processInstance = processFacadeService.getProcessInstanceByBusinessKey(contentId);
        if (processInstance.getProcessStatus().byteValue() == ProcessInstanceStatus.SUCCESS.ordinal()) {
            contentRepository.auditComplete(contentId, CmsContentStatus.AUDITED.ordinal());
        }

        return OperationResUtils.success();
    }

    @Override
    public BaseOperationRes withdraw(int auditor, String contentId, String withdrawReason) {
        boolean success = processFacadeService.completeTaskByBusinessKey(contentId, String.valueOf(auditor), withdrawReason, true);
        if (!success) {
            return OperationResUtils.fail("内容审批失败");
        }

        //结束审核流程
        contentRepository.auditComplete(contentId, CmsContentStatus.UNAPPROVED.ordinal());

        return OperationResUtils.success();
    }

    @Override
    public BaseOperationRes deleteContent(List<String> contentIdList) {
        boolean success = contentRepository.deleteContent(contentIdList);
        if (!success)
            return OperationResUtils.fail("删除内容失败");

        //删除流程实例
        processFacadeService.batchDeleteProcessInstance(contentIdList);

        return OperationResUtils.success();
    }

    @Override
    public BaseOperationRes restoreContent(List<String> contentIdList) {
        boolean success = contentRepository.restoreContent(contentIdList);
        if (!success)
            return OperationResUtils.fail("还原内容失败");

        return OperationResUtils.success();
    }
}
